import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes,allAsyncRoutes,anyRoutes } from '@/router/routes'
import { reqInfo, reqLogin, reqLogout } from '@/api/acl/login';
import router from '@/router';
import _ from 'lodash'
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

const findAllAsyncRoutes = (allAsyncRoutes:any,routes:any)=>{
 return allAsyncRoutes.filter((item)=>{
  // 过滤一级路由
      if(routes.indexOf(item.name)!=-1){
        // 过滤二级、三级、n级路由
        if(item.children&&item.children.length>0){
         item.children = findAllAsyncRoutes(item.children,routes)
        }
        return true
      }
  })
}

export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttonsList:[]
  }),

  actions: {
    //登录
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password })
        console.log(result);
        this.token = result.token
        setToken(result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取用户数据
    async getInfo() {
      try {
        let result = await reqInfo()
        this.name = result.name
        this.avatar = result.avatar
        this.buttonsList = result.buttons
        // 计算异步路由
       let useUserRegisterRoutes = findAllAsyncRoutes(_.cloneDeep(allAsyncRoutes),result.routes)
      //  动态添加异步路由和任意路由
       this.setRoute([...useUserRegisterRoutes,anyRoutes])
      //  左侧目录
       this.menuRoutes = [...staticRoutes,...useUserRegisterRoutes]
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 动态添加路由
    setRoute(registerRoutes:any){
      registerRoutes.forEach((item) => {
        router.addRoute(item)
      });
    },

    async reset() {
      try {
        await reqLogout()
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        this.resetRoute()
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }

    },
    // 清除数据
    resetRoute(){
      // 获取全部路由
      let allRoutes = router.getRoutes()
      console.log(allRoutes);
      
      // 清除全部路由
      allRoutes.filter((item)=>{
        router.removeRoute(item.name)
      })
      // 添加静态路由
      staticRoutes.forEach((item)=>{
        router.addRoute(item)
      })
    }
  },
});
